define(function (require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');

    var firstTime = true;

    var register = {
        data: {},
        init: function () {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function () {
                if ($(this).parents("a").text() == "店铺pos机注册") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initTable();
            this.initValidator();
            this.bindEvent();
        },
        /**
         * 执行查询操作.
         */
        doSearch: function () {
            $("#J_Search").data('bootstrapValidator').validate();
            if ($("#J_Search").data('bootstrapValidator').isValid()) {
                $('#table').DataTable().ajax.reload();
            }
        },
        /**
         * 初始化列表
         */
        initTable: function () {
            var self = this;
            $("#table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%",   //表格的宽度
                "sScrollXInner": "100%",   //表格的内容宽度
                "bScrollCollapse": true,  //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": false,  //是否显示分页
                "bLengthChange": false,  //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": false, //显示表格信息
                "bAutoWidth": false,  //自适应宽度
                "bServerSide": true,//开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/poscrm/api/shop/queryRegisterByCondition'),
                "fnInitComplete": function () {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function (sSource, aoData, fnCallback) {
                    if (firstTime) {
                        firstTime = false;
                        return;
                    }
                    var _data = {};
                    $($("#J_Search").serializeArray()).each(function () {
                        _data[this.name] = this.value;
                    });
                    _data.pageNum = aoData[3].value / aoData[4].value + 1;
                    _data.pageSize = aoData[4].value;
                    var dataString = JSON.stringify(_data);
                    CRM.request({
                        "type": 'POST',
                        "url": sSource,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        contentType: "application/json",
                        "success": function (req) {
                            if (req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    resultData.iTotalDisplayRecords = 999999;
                                    resultData.iTotalRecords = 999999;
                                    $.each(req.entry, function (key, entry) {
                                        resultData.aaData.push(entry)
                                        self.data[entry.id] = entry;
                                    });
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                },
                //"aaSorting": [[1, "asc"]],  //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [

                    {
                        "sTitle": "机台号",
                        "mDataProp": "sequence",
                        "bSortable": true
                    },
                    {
                        "sTitle": "机台IP",
                        "mDataProp": "iPAddress",
                        "bSortable": true
                    },
                    {
                        "sTitle": "注册时间",
                        "mDataProp": "registerTime",
                        "mRender": function (data, type, row) {
                            if (data) {
                                return CRM.formatDate(new Date(data));
                            }
                            return "";
                        }
                    },
                    {
                        "sTitle": "注册码",
                        "mDataProp": "registerCode",
                        "bSortable": true
                    },
                    {
                        "sTitle": "是否在线",
                        "mDataProp": "isOnline",
                        "mRender": function (data, type, row) {
                            var html = '离线';
                            if (data == 1) {
                                html = '在线';
                            }
                            return html;
                        }
                    },
                    {
                        "sTitle": "状态",
                        "mDataProp": "status",
                        "mRender": function (data, type, row) {
                            var html = '未激活';
                            if (data == 0) {
                                html = '删除';
                            } else if (data == 2) {
                                html = '激活';
                            } else if (data == 3) {
                                html = '过期';
                            }
                            return html;
                        }
                    },
                    {
                        "sTitle": "版本",
                        "mDataProp": "version"
                    },
                    {
                        "sTitle": "操作",
                        "bSortable": true,
                        "mDataProp": "id",
                        "mRender": function (data, type, row) {
                            var html = '<button type="button" class="btn btn-danger" onclick="javascript:deleteregister(\'' + data + '\')">删 除</button> ';
                            if (row.isSyncItemPrice) {
                                html += '<button type="button" class="btn btn-warning" onclick="javascript:updateIsSyncItemPrice(\'' + data + '\',false)">关 闭</button>';
                            } else {
                                html += '<button type="button" class="btn btn-info" onclick="javascript:updateIsSyncItemPrice(\'' + data + '\',true)">打 开</button>';
                            }

                            return html;
                        }
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "simple" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#J_Search').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                }
            });
        },
        bindEvent: function () {
            var self = this;
            $("#search_btn").on('click', function () {
                self.doSearch();
            });
            $("#add_btn").on('click', function () {
                self.save();
            });
        },
        /**
         * 显示店铺白名单
         */
        showWhiteShops: function () {
            if ($("#type").val() == 2) {
                $("#whiteShops_div").show();
            } else {
                $("#whiteShops").val("");
                $("#whiteShops_div").hide();
            }
        },
        /**
         * 保存操作
         */
        save: function () {
            var self = this;
            $("#J_Search").data('bootstrapValidator').validate();
            if ($("#J_Search").data('bootstrapValidator').isValid()) {
                if (confirm("确定新增一个POS台席？")) {
                    var _url = CRM.getOuterUrl("/poscrm/api/shop/insertRegister");
                    var dataString = {};
                    dataString.shopId = $("#shopId").val()
                    CRM.request({
                        "type": 'get',
                        "url": _url,
                        "dataType": "json",
                        contentType: "application/x-www-form-urlencoded",
                        "data": dataString,
                        "success": function (req) {
                            if (req.status) {
                                CRM.showDialog("保存成功！");
                                self.doSearch();
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                }
            }
        },
        /**
         * 删除
         * @param id
         */
        deleteregister: function (id) {
            var _url = CRM.getOuterUrl("/poscrm/api/shop/deleteRegister");
            if (!confirm('确认删除？')) {
                return;
            }
            dataString = JSON.stringify({
                id: id
            });
            CRM.request({
                "type": 'POST',
                "url": _url,
                "dataType": "json",
                contentType: "application/json",
                "data": dataString,
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog("删除成功！");
                        self.doSearch();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        /**
         * 打开/关闭 同步价格开关
         * @param id
         * @param isSyncItemPrice
         */
        updateIsSyncItemPrice: function (id, isSyncItemPrice) {
            var _url = CRM.getOuterUrl("/poscrm/api/shop/updateIsSyncItemPrice");
            dataString = JSON.stringify({
                id: id,
                isSyncItemPrice: isSyncItemPrice
            });
            CRM.request({
                "type": 'POST',
                "url": _url,
                "dataType": "json",
                contentType: "application/json",
                "data": dataString,
                "success": function (req) {
                    if (req.status) {
                        CRM.showDialog("操作成功！");
                        self.doSearch();
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        }

    };

    window.doSearch = $.proxy(register.doSearch, register);
    window.deleteregister = $.proxy(register.deleteregister, register);
    window.updateIsSyncItemPrice = $.proxy(register.updateIsSyncItemPrice, register);
    register.init();
});